<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" width="450px" :title="`${dialogProps.title}商户资料`">
    <el-form
      ref="ruleFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="env.VITE_RELEASE_NAME === 'fendi' ? rules1 : rules2"
      :disabled="dialogProps.isView"
      :model="dialogProps.row"
      :hide-required-asterisk="dialogProps.isView"
    >
      <el-form-item label="上级商户" prop="parentStoreId">
        <el-input v-model="dialogProps.row!.parentStoreName" disabled>
          <template #append> <el-button @click="openSelectTable('商户选择', 0)" :icon="MoreFilled" /> </template>
        </el-input>
      </el-form-item>
      <el-form-item label="是否创建激活码" prop="isCreateFacCode">
        <el-select class="w100" v-model="dialogProps.row!.isCreateFacCode">
          <el-option label="创建" :value="true" />
          <el-option label="不创建" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="默认密码" prop="passWord">
        <el-input v-model="dialogProps.row!.passWord" clearable></el-input>
      </el-form-item>
      <el-form-item label="连续新增数量" prop="createCount">
        <el-input-number class="w100" v-model="dialogProps.row!.createCount" :controls="false" :max="100" />
      </el-form-item>
      <el-form-item label="有效日期" prop="endDate">
        <el-date-picker class="w100" v-model="dialogProps.row!.endDate" type="date" />
      </el-form-item>
    </el-form>
    <SelectTable @radio="onRadio" ref="selectTableRef" />
    <template #footer>
      <el-button @click="dialogVisible = false"> 取消 </el-button>
      <el-button v-show="!dialogProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="ByGroupDialog">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Operation } from "@/api/interface";
import { MoreFilled } from "@element-plus/icons-vue";
import SelectTable from "@/components/SelectTable/index.vue";
import { getStoreList } from "@/api/modules/operation";

// 密码校验
const env = ref(import.meta.env);
const validatePass = (rule: any, value: any, callback: any) => {
  const finalCheckPwd =
    /^(?:(?=.*[a-z])(?=.*[A-Z])(?=.*\d)|(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_])|(?=.*[a-z])(?=.*\d)(?=.*[\W_])|(?=.*[A-Z])(?=.*\d)(?=.*[\W_])|(?=.*[A-Z])(?=.*[a-z])(?=.*[\W_])|(?=.*[A-Z])(?=.*[a-z])(?=.*\d)).{8,}$|^$/;

  // 校验密码
  const checkPwd: boolean = finalCheckPwd.test(dialogProps.value.row!.passWord);

  if (!checkPwd) {
    callback(new Error("密码必须不少于8位, 包含大小写、字母、字符至少三种"));
  } else {
    callback();
    // 注意，这个空的callback非常重要，没有它作为结束，整个校验会出问题
  }
};

const rules1 = reactive({
  // parentStoreId: [{ required: true, message: "请选择上级商户" }]
  // passWord: [{ required: true, trigger: "blur", validator: validatePass }]
});
const rules2 = reactive({
  // passWord: [{ required: true, trigger: "blur", message: "请选输入" }]
});
interface DialogProps {
  title: string;
  isView: boolean;
  isGroup?: number;
  row: Partial<Operation.ResDepartmentList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const dialogVisible = ref(false);
const dialogProps = ref<DialogProps>({
  isView: false,
  title: "",
  isGroup: 0,
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DialogProps) => {
  dialogProps.value = params;
  dialogVisible.value = true;
};

const onRadio = (row: any) => {
  dialogProps.value.row.parentStoreId = row.data.id;
  dialogProps.value.row.parentStoreName = row.data.storeName;
};

const selectTableRef = ref<InstanceType<typeof SelectTable> | null>(null);
const openSelectTable = (title: string, ix: number) => {
  const params = {
    title,
    isView: false,
    index: ix,
    initParam: { isGroup: 1 },
    selType: "radio",
    columns: [
      { type: "radio", label: "单选", width: 60 },
      { prop: "id", label: "编码", align: "left" },
      { prop: "storeName", label: "名称", align: "left" }
    ],
    api: getStoreList
  };
  selectTableRef.value?.acceptParams(params);
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await dialogProps.value.api!(dialogProps.value.row);
      ElMessage.success({ message: `${dialogProps.value.title}商户成功！` });
      dialogProps.value.getTableList!();
      dialogVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
